package com.hongxun.design.jungong.activity;

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.widget.SwipeRefreshLayout;
import android.view.View;
import android.widget.AdapterView;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.hongxun.design.MyApp;
import com.hongxun.design.R;
import com.hongxun.design.activitys.BaseActivity;
import com.hongxun.design.activitys.ChoiceModelActivity;
import com.hongxun.design.activitys.MaterialDetailActivity;
import com.hongxun.design.adapters.CodeSetModelAdapter;
import com.hongxun.design.bean.CodeSetBean;
import com.hongxun.design.bean.MaterialsBean;
import com.hongxun.design.constant.Constant;
import com.hongxun.design.interfaces.HeadSecond;
import com.hongxun.design.jungong.adapter.AdapterModelBean;
import com.hongxun.design.jungong.dialog.CreateModelDialog;
import com.hongxun.design.jungong.dialog.ModeleNameDialog;
import com.hongxun.design.listeners.ListenerSet;
import com.hongxun.design.mytools.IconSourse;
import com.hongxun.design.mytools.IntentToActivity;
import com.hongxun.design.mytools.MString;
import com.hongxun.design.mytools.SetTypeface;
import com.hongxun.design.mytools.ShardPreferencesTool;
import com.hongxun.design.mytools.ToastShow;
import com.hongxun.design.ui.headandbottonpanel.HeadSecondControlPanel;
import com.hongxun.design.ui.pickerview.lib.DensityUtil;
import com.hongxun.design.ui.ui_listview.Swipemenulistview.SwipeMenu;
import com.hongxun.design.ui.ui_listview.Swipemenulistview.SwipeMenuCreator;
import com.hongxun.design.ui.ui_listview.Swipemenulistview.SwipeMenuItem;
import com.hongxun.design.ui.ui_listview.Swipemenulistview.SwipeMenuListView;
import com.hongxun.design.ui.ui_listview.refreshlist.SwipeRefreshListView;
import com.hongxun.design.utils.DataUtil;
import com.hongxun.design.utils.fastjson.FastJsonUtil;
import com.hongxun.design.utils.httputil.HttpStringUtil;
import com.lidroid.xutils.http.RequestParams;

import java.util.ArrayList;
import java.util.List;

/**
 * 项目典设、模块
 */
public class ChoiceModelActivity_jg extends BaseActivity implements HeadSecond, ModeleNameDialog.reName {
    public String title, pro_name;
    String codeset_version_id = "";
    SwipeRefreshListView codeset_list;
    List<CodeSetBean> codeSetData;
    int startNum = 0;
    int addNum = MyApp.addNum;
    private boolean isAdd = false;
    //模块
    List<MaterialsBean> modleList;

    private Handler handler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(Message msg) {
            switch (msg.what) {
                case HttpStringUtil.SUCCESSED://下拉
                    hideWaitIngDialog();
                    codeset_list.setRefreshing(false);
                    if (FastJsonUtil.JsonToCheck(String.valueOf(msg.obj))) {
                        List<CodeSetBean> been = FastJsonUtil.JsonToData_CodeSetList(String.valueOf(msg.obj));
                        if (been == null || been.isEmpty()) return false;
                        codeSetData.clear();
                        codeSetData.addAll(been);
                        codeset_list.update();
                    } else {
                        ToastShow.showShort(mActivity, msg.obj + "");
                    }
                    break;
                case HttpStringUtil.ADDMROE://上拉
                    codeset_list.removeFooterView();
                    break;
                case 2://重命名
                case 3://收藏
                case 4://删除
                    hideWaitIngDialog();
                    if (FastJsonUtil.JsonToCheck(String.valueOf(msg.obj))) {
                        ToastShow.showShort(mActivity, MString.SUCCESSED_HTTP);
                        if (msg.what == 4) {
                            codeSetData.remove(postion_);
                            codeset_list.update();
                        } else if (msg.what == 2) {
                            codeset_list.update();
                        }
                    } else {
                        ToastShow.showShort(mActivity, "操作失败");
                    }
                    break;
                case 6://自建模块、点设
                    JSONObject object6 = JSON.parseObject(String.valueOf(msg.obj));
                    if (object6.containsKey("codesetVersionid")) {//自建模块
                        String versionid = String.valueOf(object6.get("codesetVersionid"));
                        if (versionid.length() != 0 && !versionid.equalsIgnoreCase("null")) {
                            ToastShow.showShort(mActivity, MString.SUCCESSED_HTTP);
                            startNum = 0;
                            addNum = MyApp.addNum;
                            Refresh(HttpStringUtil.SUCCESSED);
                        } else {
                            ToastShow.showShort(mActivity, "操作失败");
                        }
                    } else if (object6.containsKey("code")
                            && object6.get("code").equals("SUCCESS")) {//自建点设
                        ToastShow.showShort(mActivity, MString.SUCCESSED_HTTP);
                        startNum = 0;
                        addNum = MyApp.addNum;
                        Refresh(HttpStringUtil.SUCCESSED);
                    } else {
                        ToastShow.showShort(mActivity, "操作失败");
                    }
                    break;
                case 7://模块
                    codeset_list.setRefreshing(false);
                    if (FastJsonUtil.JsonToCheck((String) msg.obj)) {
                        if (modleList == null) {
                            modleList = FastJsonUtil.JsonToData_ModuleList2((String) msg.obj);
                        } else {
                            modleList.clear();
                            modleList.addAll(FastJsonUtil.JsonToData_ModuleList2((String) msg.obj));
                        }
                        codeset_list.update();
                    } else {
                        ToastShow.showShort(getParent(), "暂无数据");
                    }
                    break;
                case 8://nx把提交后的项目模块缓存到xml
                    List<MaterialsBean> list8 = FastJsonUtil.JsonToData_ModuleList2(String.valueOf(msg.obj));
                    ShardPreferencesTool.save(getApplicationContext(), MString.nxModelAdd, FastJsonUtil.beanToJson(list8), 3);
                    break;
                case 9://nx把提交后的项目点设缓存到xml
                    List<CodeSetBean> list9 = FastJsonUtil.JsonToData_CodeSetList(String.valueOf(msg.obj));
                    ShardPreferencesTool.save(getApplicationContext(), MString.nxDsAdd, FastJsonUtil.beanToJson(list9), 3);
                    break;
            }
            return false;
        }
    });

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_choicemodel);
        findBar();
        findView();
    }

    @SuppressLint("NewApi")
    private void getIntentData() {
        Bundle bundle = getIntent().getExtras();
        title = bundle.getString(MString.CODE, "");
        pro_name = bundle.getString(MString.project_name, "");
        codeset_version_id = MyApp.currProject.getCodeset_version_id();
    }

    @Override
    public void findBar() {
        getIntentData();
        HeadSecondControlPanel headsecond_layout = (HeadSecondControlPanel) findViewById(R.id.choice_model_head);
        headsecond_layout.initHeadPanel(DataUtil.getsecondbean("", View.GONE, R.color.bar_right,
                ListenerSet.back, "", R.color.title, View.VISIBLE, IconSourse.BACK + "", View.VISIBLE));
        headsecond_layout.setTitle(title + "：" + pro_name);
        if (MyApp.ReadOnly) {
            headsecond_layout.mRightTitle.setVisibility(View.INVISIBLE);
        }
    }

    @Override
    protected void findView() {
        findViewById(R.id.design_view).setVisibility(View.VISIBLE);
        TextView add_button = (TextView) findViewById(R.id.design_finish_button);
        TextView imporrt_tv = (TextView) findViewById(R.id.tv_importModelMterials);
        SetTypeface.set(add_button, IconSourse.ADD);
        codeset_list = (SwipeRefreshListView) findViewById(R.id.codeset_list);
        switch (title) {
            case MString.Modular:
                imporrt_tv.setVisibility(View.GONE);
                add_button.append(" 新增项目模块");
                modleList = new ArrayList<>();
                AdapterModelBean modelBean = new AdapterModelBean(this, modleList);
                codeset_list.setAdapter(modelBean, "组装项目模块功能\n" + "→点击“新增项目模块”功能\n使用项目材料进行组装；");
                codeset_list.setDivider(1);
                codeset_list.setFragment(this);
                codeset_list.setCanScroll(true);
                codeset_list.setRefreshing(true);
                Refresh(HttpStringUtil.SUCCESSED);//第一次加载
                codeset_list.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
                    @Override
                    public void onRefresh() {
                        startNum = 0;
                        addNum = MyApp.addNum;
                        Refresh(HttpStringUtil.SUCCESSED);
                    }
                });
                codeset_list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                    @Override
                    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                        Bundle bundle = new Bundle();
                        bundle.putInt(MString.TYPE, Constant.EdModel);
                        bundle.putString(MString.codeset_id, modleList.get(position).getModule_id());
                        IntentToActivity.intent(mActivity, MaterialDetailActivity.class, bundle);
                    }
                });
                break;
            case MString.ChoiceModelData:
                imporrt_tv.setVisibility(View.VISIBLE);
                SetTypeface.set(imporrt_tv, IconSourse.screen);
                add_button.append(" 新增典型组装");
                imporrt_tv.append(" 引用典型组装");
                imporrt_tv.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Bundle bundle = new Bundle();
                        bundle.putString(MString.CODE, MString.click_out);
                        bundle.putBoolean(MString.TRUE, true);
                        IntentToActivity.intent(mActivity, ChoiceModelActivity.class, bundle);
                        isAdd = true;
                    }
                });
                codeSetData = new ArrayList<>();
                CodeSetModelAdapter codesetAdapter = new CodeSetModelAdapter(codeSetData, this);
                codeset_list.setAdapter(codesetAdapter, "组装项目材料功能\n" +
                        "→点击“新增典型组装”功能\n使用项目材料进行组装；\n" +
                        "→点击“引用典型组装”功能\n使用平台内置典型设计；");
                codesetAdapter.setClick(MString.click_out);
                codesetAdapter.setCodeset_id(title);
                codesetAdapter.setJG(true);
                codeset_list.setFragment(this);
                codeset_list.setCanScroll(true);
                codeset_list.setRefreshing(true);
                Refresh(HttpStringUtil.SUCCESSED);//第一次加载
                codeset_list.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
                    @Override
                    public void onRefresh() {
                        startNum = 0;
                        addNum = MyApp.addNum;
                        Refresh(HttpStringUtil.SUCCESSED);
                    }
                });

                addDelect();
                break;
        }

        add_button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                CreateModelDialog dialog = new CreateModelDialog();
                dialog.setType(title);
                dialog.setHandler(handler);
                dialog.show(getSupportFragmentManager(), "1");
            }
        });

        super.findView();
    }

    @Override
    protected void onResume() {
        super.onResume();
        mActivity = this;
        MyApp.activity = this;
        if (isAdd) {
            startNum = 0;
            addNum = MyApp.addNum;
            Refresh(HttpStringUtil.SUCCESSED);
        }
    }

    //下拉、上拉
    private void Refresh(int handlercase) {
        codeset_version_id = MyApp.currProject.getCodeset_version_id();
        if (codeset_version_id.trim().isEmpty()) {
            codeset_list.setRefreshing(false);
            return;
        }
        switch (title) {
            case MString.Modular:
                MyApp.HTTP.getModuleList2(handler, 7, "", codeset_version_id, startNum, addNum);
                MyApp.HTTP.getModuleList2(handler, 8, "", codeset_version_id, 0, 999);
                break;
            case MString.ChoiceModelData:
                MyApp.HTTP.getCodeSetList(handler, handlercase, codeset_version_id, "", null, startNum, addNum, title, "");
                MyApp.HTTP.getCodeSetList(handler, 9, codeset_version_id, "", null, 0, 999, title, "");
                break;
        }
    }


    //加载更多
    @Override
    public void addMore() {
        super.addMore();
        startNum = addNum;
        addNum += 15;
        Refresh(HttpStringUtil.ADDMROE);
    }


    //左滑收藏
    private void addDelect() {
        final SwipeMenuCreator creator = new SwipeMenuCreator() {
            @Override
            public void create(SwipeMenu menu) {
                SwipeMenuItem item_rename = new SwipeMenuItem(getApplicationContext());
                item_rename.setBackground(getResources().getDrawable(R.mipmap.rename));
                item_rename.setWidth(DensityUtil.dip2px(getApplicationContext(), 80));
//                item_rename.setBackground(R.color.orange);
//                item_rename.setTitle("更名");

                SwipeMenuItem item_collect = new SwipeMenuItem(getApplicationContext());
                item_collect.setBackground(getResources().getDrawable(R.mipmap.collect));
                item_collect.setWidth(DensityUtil.dip2px(getApplicationContext(), 80));
//                item_collect.setBackground(R.color.colorfentlan);
//                item_collect.setTitle("收藏");

                SwipeMenuItem item_del = new SwipeMenuItem(getApplicationContext());
                item_del.setBackground(R.mipmap.del);
                item_del.setWidth(DensityUtil.dip2px(getApplicationContext(), 80));
//                item_del.setBackground(R.color.red);
//                item_del.setTitle("删除");

                menu.addMenuItem(item_rename);
                menu.addMenuItem(item_collect);
                menu.addMenuItem(item_del);
            }
        };

        codeset_list.setMenuCreator(creator, new SwipeMenuListView.OnMenuItemClickListener() {
            @Override
            public void onMenuItemClick(int position, SwipeMenu menu, int index) {
                if (MyApp.isOnLine) {
                    postion_ = position;
                    RequestParams params = new RequestParams();
                    CodeSetBean setBean = codeSetData.get(position);
                    params.addBodyParameter("codesetid", setBean.getCodeset_id());
                    if (index == 0) {
                        ModeleNameDialog dialog = new ModeleNameDialog();
                        dialog.setSetBean(setBean);
                        dialog.show(getSupportFragmentManager(), "0");
                    } else {
                        showWaitDialog(-1, "处理中...");
                        MyApp.HTTP.oprtionModel_DS(handler, params, index + 2);
                    }
                } else {
                    ToastShow.showShort(getApplicationContext(), "离线情况下不能操作典设！");
                }
            }
        });
    }

    int postion_ = 0;

    //修改名称
    @Override
    public void renameandnumber(String name, String number) {
        CodeSetBean setBean = codeSetData.get(postion_);
        switch (title) {
            case MString.Modular:
                break;
            case MString.ChoiceModelData:
                if (!setBean.getName().trim().equals(name)
                        || !setBean.getNumber().trim().equals(number)) {
                    showWaitDialog(-1, "处理中...");
                    RequestParams params = new RequestParams();
                    params.addBodyParameter("codesetid", setBean.getCodeset_id());
                    params.addBodyParameter("codesetname", name);//名称
                    params.addBodyParameter("codesetnumber", number);//编号
                    MyApp.HTTP.oprtionModel_DS(handler, params, 2);

                    setBean.setName(name);
                    setBean.setNumber(number);
                    codeSetData.set(postion_, setBean);
                }
                break;
        }
    }
}
